package de.slothsoft.bookmaker.parse.impl;

import static de.slothsoft.bookmaker.parse.impl.MangaHereDescription.REGEX_CHAPTER;
import static de.slothsoft.bookmaker.parse.impl.MangaHereDescription.REGEX_URL;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;

import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.DomSerializer;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.w3c.dom.Document;
import org.w3c.dom.xpath.XPathException;

import de.slothsoft.bookmaker.parse.ImageXPathParser;
import de.slothsoft.bookmaker.parse.OverviewParser;
import de.slothsoft.bookmaker.parse.ParseContext;
import de.slothsoft.bookmaker.parse.WebsiteDescription;
import de.slothsoft.bookmaker.parse.WebsiteParser;
import de.slothsoft.bookmaker.parse.XPathUtil;
import de.slothsoft.bookmaker.parse.OverviewParser.ParserCreator;

public class MangaHereOverviewDescription implements WebsiteDescription {

    @Override
    public String getDisplayName() {
        return "mangahere.co (Overview)";
    }

    @Override
    public boolean isSupported(String url) {
        return url.matches(REGEX_URL) && !url.matches(REGEX_CHAPTER);
    }

    @Override
    public WebsiteParser createParser(ParseContext context, InputStream input) throws IOException {
        try {
            TagNode tagNode = new HtmlCleaner().clean(input);
            Document document = new DomSerializer(new CleanerProperties()).createDOM(tagNode);
            List<String> urls = XPathUtil.findAttributes(document, "//span/a[@class='color_0077']", "href");
            return createOverviewParser(urls);
        } catch (XPathException | ParserConfigurationException | XPathExpressionException e) {
            throw new IOException(e);
        }
    }

    protected static OverviewParser createOverviewParser(List<String> chapterUrls) {
        return new OverviewParser(new ParserCreator() {

            @Override
            public ImageXPathParser createParser(InputStream input, String chapterUrl) throws IOException {
                return MangaHereDescription.createParser(input);
            }
        }, chapterUrls);
    }
}
